package cn.edu.aust.myexpri5app.utils;

import android.content.Context;

import com.apkfuns.logutils.LogUtils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import cn.edu.aust.myexpri5app.MainActivity;
import cn.edu.aust.myexpri5app.model.UserInfo;

public class FileTools {

    public static String readDataFromInner(Context context) throws IOException{
        return readDataFromInner(context,MainActivity.INNER_USER_INFO_FILE);
    }

    //从内部文件中读取原始数据，组成UTF-8串
    public static String readDataFromInner(Context context,String filename) throws IOException{
        String str="";
        FileInputStream fis=null;

        fis = context.openFileInput(filename);
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        if (buffer != null && buffer.length > 0) {
            str = new String(buffer, "utf-8");
        }

        try {
            if (fis!=null){
                fis.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return str;
    }

    public static final void writeDataToInner(Context context,String data){
        writeDataToInner(context, MainActivity.INNER_USER_INFO_FILE,data);
    }

    //将UTF-8字符串写入指定的内部文件
    public static final void writeDataToInner(Context context,String filename,String data){
        FileOutputStream fos=null;
        OutputStreamWriter osw=null;
        BufferedWriter writer=null;
        LogUtils.d(data);

        try {
            fos=context.openFileOutput(filename,Context.MODE_PRIVATE);
            osw=new OutputStreamWriter(fos,"utf-8");
            writer=new BufferedWriter(osw);

            writer.write(data,0,data.length());
            writer.newLine();
            writer.close();
            osw.close();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (writer!=null) writer.close();
                if (osw!=null) osw.close();
                if (fos!=null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
